package com.dagene.weixin.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dagene.weixin.JSONMessage;
import com.dagene.weixin.entity.WeixinUserInfo;
import com.dagene.weixin.service.UserService;
import com.dagene.weixin.util.Constants;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	@Autowired
	UserService userService;

	/**
	 * 注册并绑定账号
	 * 
	 * @param request
	 * @param info
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public JSONMessage register(HttpServletRequest request,
			@RequestBody WeixinUserInfo info) {
		JSONMessage message = new JSONMessage();
		try {
			String openid = (String) request.getSession()
					.getAttribute("weixin");
			if (openid == null) {
				message.setCode(Constants.NO_IN_WEIXIN);
				// message.setData(CoreService.getAuthURl(Constants.weixinurl
				// + "/weixiu/register.html"));
				return message;
			}

			WeixinUserInfo weixinUserInfo = userService
					.getWeixinUserInfoByOpenId(openid);
			if (weixinUserInfo == null) {
				weixinUserInfo = userService.getWeixinUserInfo(openid);
			}
			weixinUserInfo.setName(info.getName());
			weixinUserInfo.setPhone(info.getPhone());
			weixinUserInfo.setCompany(info.getCompany());
			userService.saveWeixinUserInfo(weixinUserInfo);
		} catch (Exception e) {
			e.printStackTrace();
			message.setCode(Constants.ERROR_CODE);
			message.setMessage(e.getMessage());
		}
		return message;
	}

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @param pageSize
	 * @param pageIndex
	 * @param unit
	 * @return
	 */
	@RequestMapping(value = "/queryUser", method = RequestMethod.GET)
	@ResponseBody
	public JSONMessage queryUser(HttpServletRequest request, int pageSize,
			int pageIndex, String company) {
		JSONMessage message = new JSONMessage();
		try {
			if (request.getSession().getAttribute("admin") == null) {
				message.setCode(Constants.SESSION_TIMEOUT);
			} else {
				Pageable page = new PageRequest(pageIndex, pageSize);
				Page<WeixinUserInfo> list = userService.queryUserByPage(page,
						company);
				message.setData(list.getContent());
				message.setTotal((int) list.getTotalElements());
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.setCode(Constants.ERROR_CODE);
			message.setMessage(e.getMessage());
		}
		return message;
	}

}
